package com.niji.littly_donkey_android.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.*;
import androidx.appcompat.app.AppCompatActivity;
import com.alibaba.fastjson.JSON;
import com.android.volley.*;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.JsonArray;
import com.niji.littly_donkey_android.R;
import com.niji.littly_donkey_android.http.ConnectViaSession;
import com.niji.littly_donkey_android.http.RequestManager;
import com.niji.littly_donkey_android.util.DateUtils;
import com.niji.littly_donkey_android.util.JsonUtil;
import com.niji.littly_donkey_android.util.StatusBarUtil;
import com.niji.littly_donkey_android.util.UrlUtil;
import com.qiniu.android.utils.Json;
import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import org.json.JSONException;

import java.util.*;

public class OrderFillActivity extends BaseActivity {
    private static String TAG  = "OrderFillActivity";

    /**
     * 返回按钮
     */
    private Button order_fill_return;

    /**
     * 微信支付
     */
    private RelativeLayout order_fill_wchat;

    /**
     * 支付宝支付
     */
    private RelativeLayout order_fill_alipay;

    /**
     * 清空手机号
     */
    private Button order_fill_empty_phone;

    /**
     * 清空姓名
     */
    private Button order_fill_empty_name;

    /**
     * 清空所有
     */
    private Button order_fill_empty_all;

    /***
     * 手机号
     */
    private EditText order_fill_phone;
    /**
     * 姓名
     */
    private EditText order_fill_name;

    /**
     * 票数
     */
    private TextView order_fill_tickets_number;

    /**
     * 加票
     */
    private Button order_fill_tickets_add;

    /**
     * 减票
     */
    private Button order_fill_tickets_reduce;

    private String attractionsId;

    private String playTime;

    private String ticketPrice;

    private String ticketName;

    private String uu_aid;

    private String uu_lid;

    private String uu_tid;

    private String maxLimit;

    private String minLimit;



    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.order_fill);
        init();
        orderFillreturn();
        orderWchat();
        orderAlipay();
        clearOrderFillName();
        clearOrderFillPhone();
        clearOrderFillAll();
        ticketsAdd();
        ticketsReduce();
        ticketSubmit();
    }

    private void ticketSubmit() {
        Button ticket_submit = findViewById(R.id.ticket_submit);
        ticket_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submit();
            }
        });
    }

    private void submit() {
        TextView ticket_price = findViewById(R.id.ticket_price);
        if("￥-1".equals(ticket_price.getText().toString().trim())){
            Toast.makeText(OrderFillActivity.this, "您选择的票有异常，请重新选择", Toast.LENGTH_LONG).show();
        }else {
            String fillName = order_fill_name.getText().toString().trim();
            String fillPhone = order_fill_phone.getText().toString().trim();
            if(fillName.equals("") || fillPhone.equals("")){
                Toast.makeText(OrderFillActivity.this, "游客信息不能为空", Toast.LENGTH_LONG).show();
            }else {
                String url = UrlUtil.URL + "/order/add";
                RequestQueue requestQueue= Volley.newRequestQueue(OrderFillActivity.this);
                StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        try {
                            Map<String, Object> map = JsonUtil.jsonToMap(s);
                            Integer code = (Integer) map.get("code");
                            if (code == 0) {
                                String  data = (String) map.get("data");
                                Log.i(TAG,data.toString());
                                Toast.makeText(OrderFillActivity.this, data, Toast.LENGTH_LONG).show();
                                overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                                finish();

                            } else if(code == -1){
                                Toast.makeText(OrderFillActivity.this, "登录失效，请重新登录", Toast.LENGTH_LONG).show();
                                Intent intent = new Intent(OrderFillActivity.this, GetPhoneCodeActivity.class);
                                intent.putExtra("loginCode","-1");
                                startActivity(intent);
                                finish();
                            }else {
                                String  data = (String) map.get("message");
                                Toast.makeText(OrderFillActivity.this, data, Toast.LENGTH_SHORT).show();
                                overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                                finish();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.e(TAG, volleyError.getMessage(), volleyError);
                        if(volleyError instanceof TimeoutError){
                            Toast.makeText(OrderFillActivity.this,"网络请求超时，请重试！",Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if(volleyError instanceof ServerError) {
                            Toast.makeText(OrderFillActivity.this,"服务器异常",Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if(volleyError instanceof NetworkError) {
                            Toast.makeText(OrderFillActivity.this,"请检查网络",Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if(volleyError instanceof ParseError) {
                            Toast.makeText(OrderFillActivity.this,"数据格式错误",Toast.LENGTH_SHORT).show();
                            return;
                        }

                        Toast.makeText(OrderFillActivity.this,volleyError.getMessage(),Toast.LENGTH_SHORT).show();
                    }
                }) {

                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {


                        Map<String, String> map = new HashMap<>();
                        List<Map<String,String>> list = new ArrayList<>();
                        HashMap<String, String> map1 = new HashMap<>();
                        map1.put("name",fillName);
                        map1.put("phone",fillPhone);
                        list.add(map1);
                        String s = JSON.toJSONString(list);
                        map.put("attractions_id",attractionsId);
                        map.put("tickets_number",order_fill_tickets_number.getText().toString().trim());
                        map.put("price", ticketPrice);
                        map.put("is_pay", "1");
                        map.put("tourist",s);
                        map.put("uu_aid", uu_aid);
                        map.put("uu_lid", uu_lid);
                        map.put("uu_tid", uu_tid);
                        map.put("playtime", playTime);
                        return map;
                    }

                    @Override
                    public Map<String, String> getHeaders() throws AuthFailureError {
                        String sesseionid = new ConnectViaSession(OrderFillActivity.this).GetSession();
                        if (!sesseionid.equals("")) {
                            HashMap<String, String> headers = new HashMap<String, String>();
                            headers.put("cookie", sesseionid);
                            return headers;
                        } else {
                            return super.getHeaders();
                        }
                    }
                };
                requestQueue.add(stringRequest);
            }
        }

    }

    @Override
     protected int getLayoutId() {
     return R.layout.order_fill;

     }
     @Override
     protected int getStatusBarColor() {
     return R.color.white_easy_photos;
     }
    /**
     * 减票。最少减到1
     */
    private void ticketsReduce() {
        order_fill_tickets_reduce = findViewById(R.id.order_fill_tickets_reduce);
        order_fill_tickets_reduce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String number = order_fill_tickets_number.getText().toString().trim();
                Integer ticketNum = Integer.parseInt(number);
                if(ticketNum > Integer.parseInt(minLimit)){
                    ticketNum --;
                    order_fill_tickets_number.setText( "" + ticketNum);
                }
            }
        });
    }

    /**
     * 加票
     */
    private void ticketsAdd() {
        order_fill_tickets_add = findViewById(R.id.order_fill_tickets_add);
        order_fill_tickets_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String number = order_fill_tickets_number.getText().toString().trim();
                Integer ticketNum = Integer.parseInt(number);
                ticketNum ++;
                if(ticketNum > Integer.parseInt(maxLimit)){
                    Toast.makeText(OrderFillActivity.this,"购买票数不能超过" + maxLimit + "张",Toast.LENGTH_SHORT).show();
                    ticketNum --;
                }
                order_fill_tickets_number.setText("" + ticketNum);
            }
        });
    }

    /**
     * 清空所有
     */
    private void clearOrderFillAll() {
        order_fill_empty_all = findViewById(R.id.order_fill_empty_all);
        order_fill_empty_all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                order_fill_phone.setText("");
                order_fill_name.setText("");
            }
        });
    }

    /**
     * 清空手机号
     */
    private void clearOrderFillPhone() {
        order_fill_empty_phone = findViewById(R.id.order_fill_empty_phone);
        order_fill_phone = findViewById(R.id.order_fill_phone);
        order_fill_empty_phone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                order_fill_phone.setText("");
            }
        });

    }

    /**
     * 清空姓名
     */
    private void clearOrderFillName() {
        order_fill_empty_name = findViewById(R.id.order_fill_empty_name);
        order_fill_name = findViewById(R.id.order_fill_name);
        order_fill_empty_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                order_fill_name.setText("");
            }
        });

    }

    private void init() {
        TextView ticket_price = findViewById(R.id.ticket_price);
        TextView ticket_name = findViewById(R.id.ticket_name);
        order_fill_alipay = findViewById(R.id.order_fill_alipay);
        order_fill_wchat = findViewById(R.id.order_fill_wChat);
        order_fill_tickets_number = findViewById(R.id.order_fill_tickets_number);
        TextView ticket_subscribe_time = findViewById(R.id.ticket_subscribe_time);
        Intent intent = getIntent();
        attractionsId = intent.getStringExtra("attractions_id");
        playTime = intent.getStringExtra("playtime");
        ticketPrice = intent.getStringExtra("ticketPrice");
        ticketName = intent.getStringExtra("ticketName");
        uu_tid = intent.getStringExtra("uu_tid");
        uu_lid = intent.getStringExtra("uu_lid");
        uu_aid = intent.getStringExtra("uu_aid");
        ticket_name.setText(ticketName);
        ticket_price.setText("￥" + ticketPrice);
        ticket_subscribe_time.setText(playTime);
        showTicketInfo(Integer.parseInt(attractionsId));
    }

    private void showTicketInfo(int id){
        RelativeLayout order_file_loading = findViewById(R.id.order_file_loading);
        RelativeLayout order_fill_main = findViewById(R.id.order_fill_main);
        order_file_loading.setVisibility(View.VISIBLE);
        TextView ticket_price = findViewById(R.id.ticket_price);
        TextView ticket_subscribe_time = findViewById(R.id.ticket_subscribe_time);
        TextView ticket_name = findViewById(R.id.ticket_name);
        String url = UrlUtil.URL + "/attractions/ticket/list?attractions_id=" + id;

        RequestQueue requestQueue= Volley.newRequestQueue(OrderFillActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    Map<String, Object> map = JsonUtil.jsonToMap(s);
                    Integer code = (Integer) map.get("code");
                    if (code == 0) {
                        ArrayList<Map<String,Object>> data = (ArrayList<Map<String, Object>>) map.get("data");
                        Log.i(TAG,data.toString());
                        if(data != null){
                            if(data.size() > 0){
                                maxLimit = (String) data.get(0).get("UUbuy_limit_up");
                                minLimit = (String) data.get(0).get("UUbuy_limit_low");
//                                ticket_price.setText(ticketPrice + "￥");
//                                ticket_name.setText(UUtitle);
                                order_file_loading.setVisibility(View.INVISIBLE);
                                order_fill_main.setVisibility(View.VISIBLE);
                            }
                        }



                    } else if(code == -1){
                        Toast.makeText(OrderFillActivity.this, "登录失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(OrderFillActivity.this, GetPhoneCodeActivity.class);
                        intent.putExtra("loginCode","-1");
                        startActivity(intent);
                        finish();
                    }else {
                        String  data = (String) map.get("message");
                        Toast.makeText(OrderFillActivity.this, data, Toast.LENGTH_SHORT).show();
                        overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                        finish();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.e(TAG, volleyError.getMessage(), volleyError);
                if(volleyError instanceof TimeoutError){
                    Toast.makeText(OrderFillActivity.this,"网络请求超时，请重试！",Toast.LENGTH_SHORT).show();
                    overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                    finish();
                    return;
                }
                if(volleyError instanceof ServerError) {
                    Toast.makeText(OrderFillActivity.this,"服务器异常",Toast.LENGTH_SHORT).show();
                    overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                    finish();
                    return;
                }
                if(volleyError instanceof NetworkError) {
                    Toast.makeText(OrderFillActivity.this,"请检查网络",Toast.LENGTH_SHORT).show();
                    overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                    finish();
                    return;
                }
                if(volleyError instanceof ParseError) {
                    Toast.makeText(OrderFillActivity.this,"数据格式错误",Toast.LENGTH_SHORT).show();
                    overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                    finish();
                    return;
                }

                Toast.makeText(OrderFillActivity.this,volleyError.getMessage(),Toast.LENGTH_SHORT).show();
                overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                finish();
            }
        }) {

            @Override
            public Request<?> setRetryPolicy(RetryPolicy retryPolicy) {


                return super.setRetryPolicy(new DefaultRetryPolicy(5000,3,1.0F));
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                String sesseionid = new ConnectViaSession(OrderFillActivity.this).GetSession();
                if (!sesseionid.equals("")) {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("cookie", sesseionid);
                    return headers;
                } else {
                    return super.getHeaders();
                }
            }
        };
        requestQueue.add(stringRequest);

    }

    /***
     * 支付宝支付
     */
    private void orderAlipay() {
        order_fill_alipay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                order_fill_alipay.setBackground(getResources().getDrawable(R.drawable.order_file_pay));
                order_fill_wchat.setBackground(getResources().getDrawable(R.drawable.order_file_pay_grey));

            }
        });
    }

    /**
     * 微信支付
     */
    private void orderWchat() {
        order_fill_wchat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                order_fill_alipay.setBackground(getResources().getDrawable(R.drawable.order_file_pay_grey));
                order_fill_wchat.setBackground(getResources().getDrawable(R.drawable.order_file_pay));

            }
        });
    }

    private void orderFillreturn() {
        order_fill_return = findViewById(R.id.order_fill_return);
        order_fill_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                overridePendingTransition(R.anim.xpage_slide_in_left,R.anim.xpage_slide_out_right);
                finish();
            }
        });
    }


}
